package com.base.cn.platform.os.interceptor;


import com.base.cn.platform.os.common.AdminFunctionUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.LoginUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.function.SysFunctionService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 认证拦截
 */
@Component
public class SysAuthenticationInterceptor implements HandlerInterceptor {

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    @Autowired
    private LoginUtil loginUtil;
    @Autowired
    private SysFunctionService sysFunctionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //验证权限
        String uri = request.getRequestURI();
        uri = uri.replace(WebUtils.getContextPath(request),"");
        if(uri.contains("toLiveByLink")){
            return true;
        }
        // 未登录跳转登录页面
        if(!loginUtil.isLogin(request)){
            if(WebUtils.isAjaxRequest(request)){
                response.setCharacterEncoding("utf-8");
                Map<String,Object> resultMap = ResultUtil.ERROR("登录过期，请重新登录");
                resultMap.put("NOT_LOGIN","NOT_LOGIN");
                response.getWriter().print(gson.toJson(resultMap));
            }else{
                response.sendRedirect(WebUtils.getContextPath(request)+"/notLoginJump");
            }
            return false;
        }
        //logger.info("--------------权限拦截uri:"+uri);
        //查询系统中所有url不空的权限
        List<Map<String,Object>> allFunction = sysFunctionService.findAllCacheSysFunctionList();
        if(ObjectUtils.isNotEmpty(allFunction)){
            List<Map<String,Object>> userAllFunction = sysFunctionService.findUserFunctionList(loginUtil.getLoginUserId(request));
            //对比权限URL
            boolean isOk = this.contrastUrlFunction(uri,userAllFunction,allFunction,request);
            //通过对比结果返回状态
            if(!isOk){//没有权限跳转
                if(WebUtils.isAjaxRequest(request)){
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().print(gson.toJson(ResultUtil.ERROR("没有操作权限")));
                }else{
                    response.sendRedirect(WebUtils.getContextPath(request)+"/noAuthority");
                }
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    /**
     * url角色与用户角色对比
     * @param currentUri 当前访问的URI
     * @param userAllFunction 用户的所有的权限的URL
     * @param allFunction 系统所有的权限
     * @return true可以，false不可以
     */
    private boolean contrastUrlFunction(String currentUri, List<Map<String,Object>> userAllFunction, List<Map<String,Object>> allFunction,HttpServletRequest request){
        if(ObjectUtils.isNotEmpty(allFunction) && StringUtils.isNotEmpty(currentUri)){
            Map<String,Map<String,Object>> allFunctionMaps = allFunction.stream().filter(e-> StringUtils.isNotEmpty((String)e.get("functionUrl"))).collect(Collectors.toMap(e->(String)e.get("functionUrl"),e->e,(x,y)-> y));
            Map<String,Object> currentFunctionMap = allFunctionMaps.get(currentUri);
            //如果访问的url不在权限管理中，直接通过验证
            if(currentFunctionMap==null){
                return true;
            }
            Map<String,Map<String,Object>> userAllFunctionMaps = userAllFunction.stream().filter(e->StringUtils.isNotEmpty((String)e.get("functionUrl"))).collect(Collectors.toMap(e->(String)e.get("functionUrl"),e->e,(x,y)-> y));
            currentFunctionMap = userAllFunctionMaps.get(currentUri);
            //如果用户拥有该url的访问权限
            if(currentFunctionMap!=null){
                //获取访问面包屑
                List<Map<String,Object>> functionLink = AdminFunctionUtils.getRequestLink(currentUri,allFunction);
                request.setAttribute("functionLink",functionLink);
                //当前访问的权限名
                request.setAttribute("pageTitle",currentFunctionMap.get("functionName"));
                //权限说明
                request.setAttribute("functionDepict",currentFunctionMap.get("depict"));
                //权限重要信息内容
                request.setAttribute("functionMajorInfo",currentFunctionMap.get("majorInfo"));
                //有权限访问
                return true;
            }
        }
        BigDecimal userId = loginUtil.getLoginUserId(request);
        if(userId.compareTo(new BigDecimal(1))==0){//超级管理员不过滤
            return true;
        }
        return false;
    }


}
